const JWT = require("./JWT")
const encryption = require("./encryption")
const loginAndSession = require("./loginAndSession")
const DateFormat = require("../util/dateFormat")
const { socketTokenCheck} = require("../util/socketTokenCheck")

exports.tokenCheck = async (token,clientIp,sessionInfo)=>{
    let newToken
    let {sessionid,personid} = sessionInfo
    if(token){
        let playload = JWT.verify(token) //token校验
        // console.log(playload)
        if(playload.status === false){      
            //token过期     
            let noActiveDatas = [sessionid]            
            let loginLogDatas = [personid,clientIp,'FORCE_LOGOUT','SUCCESS']
            //用户登录日志数据-异步写入数据库
            loginAndSession.addLog(loginLogDatas) 
            //更新session 
            await loginAndSession.logoutSession(noActiveDatas) 
            return{
                status:playload.status,
                msg: playload.msg,
            }   
        }
        else{
            //token未过期
            let tokenExp = DateFormat.dateFormat(playload.exp*1000)  
            let tcDatas = [playload.personid,clientIp,tokenExp]
            let tc = await loginAndSession.tokenHashCheck(tcDatas) //获取token加密值
            let tokenIsMatch = tc.length === 0 ? false
                                            : await encryption.tokenIsMatch(token,tc[0].TOKEN_HASH) //token加密值校验            
            if(tokenIsMatch){
                // 续航token
                newToken = JWT.generate({
                                    username:playload.username,
                                    personid:playload.personid
                                },"1h")
                let newPlayload = JWT.verify(newToken) 
                // console.log(newPlayload)                
                let newTokenExp = DateFormat.dateFormat(newPlayload.exp*1000)
                let newTokenHash = await encryption.hashedToken(newToken)
                // 更新session 
                let newTcDatas = [newTokenHash,newTokenExp,tc[0].SESSION_ID]
                await loginAndSession.updateSession(newTcDatas)  
                // 用户登录日志数据-异步写入数据库
                let newloginLogDatas = [personid,clientIp,'RENEW','SUCCESS']  
                loginAndSession.addLog(newloginLogDatas)
                // 刷新token任务
                socketTokenCheck(newToken)
                return newToken  
            }else{
                //token加密值校验失败
                return {
                    status:false,
                    msg:"已被管理员清理，请重新登录"
                }
            }                  
        }        
    }else{       
        return false
    }        
}    
